package com.xsq.page;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jay.easykeyboard.SystemKeyboard;
import com.jay.easykeyboard.action.KeyBoardActionListence;
import com.xsq.Constants;
import com.xsq.R;
import com.xsq.data.CardInfo;
import com.xsq.utils.HttpUtil;
import com.xsq.utils.MyInputFilter;
import com.xsq.utils.StatusUtils;
import com.xsq.utils.Utils;
import com.xsq.view.RecordsDialog;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.math.BigDecimal;
import java.util.HashMap;

@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity implements View.OnClickListener {

    @ViewInject(R.id.card_no)
    private TextView cardNoText;
    @ViewInject(R.id.user_name)
    private TextView userNameText;
    @ViewInject(R.id.user_code)
    private TextView userCodeText;
    @ViewInject(R.id.card_status)
    private TextView cardStatusText;
    @ViewInject(R.id.edit_yingshou)
    private EditText editYs;
    @ViewInject(R.id.edit_shishou)
    private EditText editSs;
    @ViewInject(R.id.submit_btn)
    private Button submitBtn;
    @ViewInject(R.id.consume_btn)
    private Button consumeBtn;
    @ViewInject(R.id.keyboard)
    private SystemKeyboard keyboard;

    private Gson gson = new Gson();
    private CardInfo cardInfo;

    private NfcAdapter nfcAdapter;
    private PendingIntent mPendingIntent;
    private Tag tag;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String cardNo = msg.obj.toString();
                    cardNoText.setText(cardNo);
                    fetchCardInfo(cardNo);
                    break;
                case 2:
                    cardNoText.setText("");
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        hideBottomUIMenu();

        initNfc();
        editYs.setInputType(InputType.TYPE_NULL|InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        editSs.setInputType(InputType.TYPE_NULL|InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        editYs.setFilters(new InputFilter[]{new MyInputFilter(2)});
        editSs.setFilters(new InputFilter[]{new MyInputFilter(2)});
        editYs.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {
                    keyboard.setEditText(editYs);
                }
            }
        });
        editSs.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {
                    keyboard.setEditText(editSs);
                }
            }
        });

        keyboard.setOnKeyboardActionListener(new KeyBoardActionListence() {
            @Override
            public void onComplete() {

            }

            @Override
            public void onTextChange(Editable editable) {

            }

            @Override
            public void onClear() {

            }

            @Override
            public void onClearAll() {

            }
        });
        editYs.requestFocus();
        submitBtn.setOnClickListener(this);
        consumeBtn.setOnClickListener(this);
    }

    @SuppressLint("NewApi")
    private void initNfc() {
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            Toast.makeText(this, "设备不支持NFC功能", Toast.LENGTH_SHORT).show();
            finish();
        }else {
            if (!nfcAdapter.isEnabled()) {
                AlertDialog dialog = new AlertDialog.Builder(this)
                        .setMessage(getString(R.string.nfc_not_open_go_open))
                        .setPositiveButton(getString(R.string.yes),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        Intent intent = new Intent(
                                                "android.settings.NFC_SETTINGS");
                                        startActivityForResult(intent, 100);
                                    }
                                }).create();
                dialog.show();
            }
            mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);
        }
    }

    @SuppressLint("NewApi")
    @Override
    protected void onResume() {
        super.onResume();
        if (nfcAdapter != null) {
            nfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
        }
    }

    private void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            View decorView = this.getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View
                    .SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);

        }
    }

    private void clear() {
        cardInfo = null;
        fillCardInfo(cardInfo);
        editSs.setText("");
        editYs.setText("");
        editYs.requestFocus();
    }

    private void fetchCardInfo(String cardNo) {
        HashMap<String, String> params = new HashMap<>();
        params.put("posSn", Utils.getAndroidId(this));
        params.put("cardNo", cardNo);
        HttpUtil.getInstance().post(getBaseUrl() + Constants.url_checkCard, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response==" + response.toString());
                int code = response.optInt("code");
                if(code == 0) {
                    cardInfo = gson.fromJson(response.optString("consumeUser"), CardInfo.class);
                    fillCardInfo(cardInfo);
                }else {
                    showToast(response.optString("msg"));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                StatusUtils.handleError(ex, MainActivity.this);
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                /*String ddddd = "{\"consumeUser\":{\"userCode\":\"123\",\"userName\":\"张三\",\"userType\":\"0\",\"userStatus\":\"1\",\"accountId\":\"3b3acee7b02b4d94b10800f003d53dda\",\"accountBalance\":10,\"openAccountMoney\":10,\"limitOneDay\":5,\"accountStatus\":\"1\",\"cardNo\":\"eae44173\",\"cardType\":null,\"cardSerialNo\":\"\",\"cardStatus\":\"1\",\"orgCode\":\"PLA-NJACC\"}}";
                cardInfo = gson.fromJson(ddddd, CardInfo.class);
                fillCardInfo(cardInfo);*/
            }
        });
    }

    private void reportConsumeRecords(String cardNo, int orderAmount, int actualAmount, int discountAmount) {
        HashMap<String, String> params = new HashMap<>();
        params.put("posSn", Utils.getAndroidId(this));
        params.put("merchantNo", getMerId());
        params.put("windowNo", getWinId());
        params.put("cardNo", cardNo);
        params.put("orderAmount", String.valueOf(orderAmount));
        params.put("actualAmount", String.valueOf(actualAmount));
        params.put("discountAmount", String.valueOf(discountAmount));
        HttpUtil.getInstance().post(getBaseUrl() + Constants.url_reportConsumeRecords, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response==" + response.toString());
                clear();
                showToast(response.optString("msg"));
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                StatusUtils.handleError(ex, MainActivity.this);
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                /*String ddddd = "{\"msg\": \"操作成功\"}";
                showToast("操作成功");*/
            }
        });
    }

    private void fillCardInfo(CardInfo cardInfo) {
        if(cardInfo != null) {
            cardNoText.setText(cardInfo.getCardNo());
            String cardStatus = "";
            switch (Integer.valueOf(cardInfo.getCardStatus())) {
                case -1:
                    cardStatus = "未发卡";
                    break;
                case 0:
                    cardStatus = "停用";
                    break;
                case 1:
                    cardStatus = "正常";
                    break;
                case 2:
                    cardStatus = "解挂";
                    break;
                case 3:
                    cardStatus = "挂失";
                    break;
                case 4:
                    cardStatus = "换卡";
                    break;

            }
            cardStatusText.setText(cardStatus);
            userNameText.setText(cardInfo.getUserName());
            userCodeText.setText(cardInfo.getUserCode());
        }else {
            cardNoText.setText("");
            cardStatusText.setText("");
            userNameText.setText("");
            userCodeText.setText("");
        }
    }

    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
            //System.out.println(buffer);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }

    @SuppressWarnings("static-access")
    @SuppressLint("NewApi")
    protected void onNewIntent(Intent intent) {
        Message message = new Message();
        message.what = 2;
        handler.sendMessage(message);
        tag = intent.getParcelableExtra(nfcAdapter.EXTRA_TAG);
        if (tag == null)
            return;
        @SuppressWarnings("unused")
        final byte[] id = tag.getId();

        String str = bytesToHexString(tag.getId());
        Message message2 = new Message();
        message2.what = 1;
        message2.obj = str;
        handler.sendMessage(message2);
    }

    @SuppressLint("NewApi")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            nfcAdapter = NfcAdapter.getDefaultAdapter(this);
            if (!nfcAdapter.isEnabled()) {
                showToast("设备没有打开NFC功能");
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.submit_btn:
                String orderAmountText = editYs.getText().toString();
                String actualAmountText = editSs.getText().toString();
                if(TextUtils.isEmpty(orderAmountText) || TextUtils.isEmpty(actualAmountText)) {
                    showToast("请输入应收金额和实收金额");
                    return;
                }
                BigDecimal orderAmountDec = new BigDecimal(orderAmountText);
                BigDecimal actualAmountDec = new BigDecimal(actualAmountText);
                BigDecimal discountAmountDec = orderAmountDec.subtract(actualAmountDec);
                int orderAmount = orderAmountDec.multiply(new BigDecimal(100)).intValue();
                int actualAmount = actualAmountDec.multiply(new BigDecimal(100)).intValue();
                int discountAmount = discountAmountDec.multiply(new BigDecimal(100)).intValue();
                if(orderAmount > 1000000) {
                    showToast("数额太大");
                    return;
                }
                if(orderAmount < actualAmount) {
                    showToast("实收不能大于应收");
                    return;
                }
                if(cardInfo == null) {
                    showToast("未刷卡或卡不存在");
                }else {
                    int cardStatus = Integer.valueOf(cardInfo.getCardStatus());
                    if(cardStatus == 1 || cardStatus == 2 || cardStatus == 4) {
                        reportConsumeRecords(cardInfo.getCardNo(), orderAmount, actualAmount, discountAmount);
                    }else {
                        showToast("卡状态不支持刷卡，请联系管理员");
                    }
                }
                break;
            case R.id.consume_btn:
                RecordsDialog recordsDialog = new RecordsDialog(this, "当日交易流水");
                recordsDialog.show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}
